#pragma once

#include <iostream>
#include <memory>

#include <cstring>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "Log.hpp"
#include "Inet.hpp"

namespace socket_ddsm
{
    // 展开日志命名空间
    using namespace log_ddsm;

    // 默认port，gblck
    const static int gport = 8888;
    const static int gblcklog = 8;

    enum
    {
        SOCK_CREAT_FAIL = 1,
        BIND_FAIL,
        LISTEN_FAIL,

        MSSIZE = 4096
    };

    // 对Socket的前置声明
    class Socket;
    // 是一个类型名，可用于接受std::make_shared<TcpSocket>()的返回值
    using SockSPtr = std::shared_ptr<Socket>;

    // 模板方法类模式
    /*基类提供方法，并组合，具体实现在派生类的实现*/
    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;

        virtual void BindOrDie(uint16_t port) = 0;

        virtual void ListenOrDie(int blcklog = gblcklog) = 0;

        virtual SockSPtr Accepter(Inet *addr) = 0;

        virtual bool Connector(const std::string &peerip, uint16_t peerport) = 0;

        virtual int GetSocket() = 0;

        virtual void Close() = 0;

        virtual ssize_t Recv(std::string *out) = 0; // 输出型参数,out把接受到的消息带出来

        virtual ssize_t Send(const std::string &in) = 0;

    public:
        // 组合的创建Tcp的方法集合
        void BuildListenSocket(int port = gport)
        {
            CreateSocketOrDie();
            BindOrDie(port);
            ListenOrDie();
        }

        void BuildNormalSocket(const std::string &peerip, uint16_t peerport)
        {
            CreateSocketOrDie();
            Connector(peerip, peerport);
        }

        // void BuildUdpSocket()
        // {}
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
            : _socket()
        {
        }

        TcpSocket(int socket)
            : _socket(socket)
        {
        }

        ~TcpSocket()
        {
            Close();
        }

        void CreateSocketOrDie() override
        {
            // 1.以tcp方式创建网络套接字
            _socket = socket(AF_INET, SOCK_STREAM, 0);
            if (_socket < 0)
            {
                LOG(FATAL, "socket create fail!\n");
                exit(SOCK_CREAT_FAIL);
            }
            LOG(DEBUG, "create sockfd success socket: %d\n", _socket);
        }

        void BindOrDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));

            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            // 本主机的任意ip地址都可访问此localport
            local.sin_addr.s_addr = INADDR_ANY;

            int n = bind(_socket, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind fail!\n");
                exit(BIND_FAIL);
            }
            LOG(DEBUG, "bind success\n");
        }

        void ListenOrDie(int blcklog) override
        {
            // 将socket设置为listen状态
            //  tcp是面向连接的，tcp需要不断的能够获取连接
            int n = listen(_socket, blcklog);
            if (n < 0)
            {
                LOG(FATAL, "listen fail");
                exit(LISTEN_FAIL);
            }
            LOG(DEBUG, "listen success\n");
        }

        SockSPtr Accepter(Inet *peer) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 输出型参数，获取client
            int rwfd = accept(_socket, (struct sockaddr *)&client, &len);
            if (rwfd < 0)
            {
                // 获取读写fd失败，对整体获取无影响；如果失败，则再次尝试获取即可
                LOG(WARNING, "accept error\n");
                return nullptr;
            }
            // 想要打印客户端信息——需要构造INET类(用于维护网络转化为主机的class)
            *peer = Inet(client);
            LOG(INFO, "accept success ,client info: %s\n", peer->UniqueName().c_str());

            return std::make_shared<TcpSocket>(rwfd); // C++14 ---基类指针指向派生类对象
        }

        // 返回值为bool，成功true，失败false，成功与否通过上层来判断
        bool Connector(const std::string &peerip, uint16_t peerport) override
        {
            // connect完成后server的accept会返回
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

            int n = ::connect(_socket, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                return false;
            }
            return true;
        }
        int GetSocket() override
        {
            return _socket;
        }
        void Close() override
        {
            if (_socket > 0)
            {
                int reval = ::close(_socket);
                if (reval < 0)
                {
                    LOG(ERROR, "_socket close error\n");
                }
            }
        }
        ssize_t Recv(std::string *out) override
        {
            char buf[MSSIZE] = {0};
            int n = ::recv(_socket, buf, sizeof(buf), 0);
            if (n > 0) // 读成功
            {
                buf[n] = 0;
                *out = buf;
            }
            return n;
        }

        ssize_t Send(const std::string &in) override
        {
            return ::send(_socket, in.c_str(), in.size(), 0);
        }

    private:
        int _socket;
    };

} // namespace socket_ddsm
